/*
 * Created on Jun 9, 2005
 *
 */
package com.erclab.internal.xpresso.security;

import com.erclab.internal.xpresso.Resource;
import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.dataAccess.ApplicationDataSource;
import com.erclab.internal.xpresso.dataAccess.GenericResultSet;
import com.erclab.internal.xpresso.dataAccess.Query;
import com.erclab.internal.xpresso.exceptions.DataSourceException;

/**
 * @author Enrique Rodriguez.
 *
 */
public class MySqlAccessController implements AccessController {

	protected static final String VALIDATION_QUERY = "SELECT IdUser FROM usr_users WHERE UserName=? AND Password=?";
	protected static final String ACCESS_ALL_CATEGORY = "All";

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.security.AccessController#isAllowedToUseResource(com.erclab.internal.xpresso.Resource, com.erclab.internal.xpresso.security.User)
	 */
	public boolean isAllowedToUseResource(Resource theResource, User theUser) {
		if (theResource.getCategory() != null && theResource.getCategory().equalsIgnoreCase(ACCESS_ALL_CATEGORY))
			return true;
			 
		if (theResource.getCategory() == null || theUser.getRoles() == null){
			return false;
		}
		for (int i = 0; i < theUser.getRoles().length; i++){
			if(theUser.getRoles()[i] != null && theUser.getRoles()[i].equalsIgnoreCase(theResource.getCategory())){
				return true;
			}
		}
		return false;
	}

	public boolean validateCredentials(SecurityCredentials sc) throws DataSourceException { 
		ApplicationDataSource ads = Settings.getRepository().getApplicationDataSource(Settings.getDirectoryIdDataSource());
		Query q = new Query();
		q.setQuery(VALIDATION_QUERY);
		q.setValues(new String[]{sc.getUserName(), sc.getPassword()});
		GenericResultSet grs = ads.runQuery(q);
		if (grs.nextRow()){
			return true;
		}
		return false;
	}

}
